// API服务工具，统一处理与Python后端的通信

// Python后端API基础URL
const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://127.0.0.1:8000';

/**
 * 发送API请求的基础函数
 * @param {string} endpoint - API端点路径
 * @param {string} method - HTTP方法
 * @param {Object} data - 请求体数据
 * @param {Object} options - 额外选项
 * @returns {Promise} - 返回请求结果
 */
export async function apiRequest(endpoint, method = 'GET', data = null, options = {}) {
  try {
    const headers = {
      'Content-Type': 'application/json',
      ...options.headers,
    };

    const config = {
      method,
      headers,
    };

    if (data) {
      config.body = JSON.stringify(data);
    }

    // 确保endpoint不以/开头
    const cleanEndpoint = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint;
    const response = await fetch(`${API_BASE_URL}/${cleanEndpoint}`, config);
    
    // 处理流式响应
    if (response.headers.get('content-type')?.includes('text/plain') && 
        response.headers.get('transfer-encoding') === 'chunked') {
      return response.body;
    }
    
    // 优雅处理非JSON错误响应
    let result;
    const contentType = response.headers.get('content-type') || '';
    if (contentType.includes('application/json')) {
      result = await response.json();
    } else {
      const text = await response.text();
      if (!response.ok) {
        throw new Error(text || `API请求失败: ${response.status}`);
      }
      try {
        result = JSON.parse(text);
      } catch {
        result = { data: text };
      }
    }

    if (!response.ok) {
      throw new Error(result.error || `API请求失败: ${response.status}`);
    }

    return result;
  } catch (error) {
    console.error(`API请求错误 (${endpoint}):`, error);
    throw error;
  }
}

/**
 * 发送需要授权的API请求
 * @param {string} endpoint - API端点路径
 * @param {string} method - HTTP方法
 * @param {Object} data - 请求体数据
 * @param {Object} options - 额外选项
 * @returns {Promise} - 返回请求结果
 */
export async function authenticatedApiRequest(endpoint, method = 'GET', data = null, options = {}) {
  // 从cookie或localStorage获取token
  const token = await getAuthToken();
  
  if (!token) {
    throw new Error('未授权，请先登录');
  }
  
  const headers = {
    'Authorization': `Bearer ${token}`,
    ...options.headers,
  };
  
  return apiRequest(endpoint, method, data, { ...options, headers });
}

/**
 * 获取认证token
 * @returns {Promise<string>} - 返回认证token
 */
async function getAuthToken() {
  try {
    // 检查是否在服务器端环境
    const isServer = typeof window === 'undefined';
    
    if (isServer) {
      // 服务器端：使用getServerSession获取会话信息
      const { getServerSession } = await import('next-auth/next');
      const { authOptions } = await import('@/app/api/auth/[...nextauth]/route');
      const session = await getServerSession(authOptions);
      
      // 确保返回的是字符串类型的token
      const token = session?.user?.accessToken || '';
      return typeof token === 'string' ? token : '';
    } else {
      // 客户端：使用传统的fetch方式
      const res = await fetch('/api/auth/session');
      if (!res.ok) {
        throw new Error('Failed to fetch session');
      }
      const session = await res.json();
      
      // 确保返回的是字符串类型的token
      const token = session?.user?.accessToken || '';
      return typeof token === 'string' ? token : '';
    }
  } catch (error) {
    console.error('获取认证token失败:', error);
    return '';
  }
}

// 导出常用的API方法
export const api = {
  get: (endpoint, options = {}) => apiRequest(endpoint, 'GET', null, options),
  post: (endpoint, data, options = {}) => apiRequest(endpoint, 'POST', data, options),
  put: (endpoint, data, options = {}) => apiRequest(endpoint, 'PUT', data, options),
  delete: (endpoint, options = {}) => apiRequest(endpoint, 'DELETE', null, options),
  patch: (endpoint, data, options = {}) => apiRequest(endpoint, 'PATCH', data, options),
  // 认证相关API
  auth: {
    get: (endpoint, options = {}) => authenticatedApiRequest(endpoint, 'GET', null, options),
    post: (endpoint, data, options = {}) => authenticatedApiRequest(endpoint, 'POST', data, options),
    put: (endpoint, data, options = {}) => authenticatedApiRequest(endpoint, 'PUT', data, options),
    delete: (endpoint, options = {}) => authenticatedApiRequest(endpoint, 'DELETE', null, options),
    patch: (endpoint, data, options = {}) => authenticatedApiRequest(endpoint, 'PATCH', data, options),
  },
};

// 获取当前API基础URL
export function getApiBaseUrl() {
  return API_BASE_URL;
}